package utils.version5;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

class TxInvocationHandler implements InvocationHandler {
    private  TransactionManager transactionManager;
    private  Object target;

    public TxInvocationHandler(Object target,TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        try {
            transactionManager.start();
            result = method.invoke(target, args);
            transactionManager.commit();
        }catch (RuntimeException e) {
            transactionManager.rollback();
            System.out.println(e.getMessage());
            throw e;
        }finally {
            transactionManager.getFactory().close();
        }
        return  result;
    }
}
